/*
 * Copyright 2009 Armando Blancas
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package taskgraph.tasks.io;

import java.io.IOException;
import java.io.InterruptedIOException;

import taskgraph.ports.CharInputPort;
import taskgraph.tasks.PrimitiveTask;


/**
 * Sink task for the Standard Error stream.
 *  
 * <p>The contents is read from the char output port as-is,
 * without filtering out line separators or any other characters.
 * 
 * @author Armando Blancas
 * @see taskgraph.ports.CharInputPort
 */
public class StandardError extends PrimitiveTask {

	private CharInputPort input;

	/**
	 * This constructor allows creating instances as beans.
	 */
    public StandardError() {
    	// do nothing
    }

	/**
     * Creates a fully configured instance.
     * 
     * @param input The char input port.
     */
    public StandardError(final CharInputPort input) {
    	setInput(input);
    }

    /**
     * Gets the intput port.
     * 
	 * @return The char input port.
	 */
	public CharInputPort getInput() {
		return input;
	}

    /**
	 * Reads the input port and writes it to the standard error.
	 *<pre>
	 *while not EOF
	 *    read characters from pipe
	 *    write characters to stderr
	 *close input port
	 *</pre>
	 */
	@Override
    public void run() {
    	try {
    		while (!Thread.currentThread().isInterrupted()) {
    			String line = input.readLine();
    			if (line == null) {
    				break;
    			}
    			System.err.println(line);
            }
        } catch (InterruptedIOException ie) {
        	// interruption request
        } catch (IOException ioe) {
        	// pipe synch error
            log.error("StandardError#run()", ioe);
        } finally {
			input.close();
        }
    }

	/**
	 * Sets the input port.
	 * 
	 * @param input The char input port.
	 */
    public void setInput(final CharInputPort input) {
    	if (input == null)
    		throw new IllegalArgumentException("input == null");
 		this.input = input;
	}

}
